#include<vector>
using namespace std;

int findTargetSumWays(vector<int>& nums, int target) {
    int n = nums.size(), sum = 0;
    for (auto x : nums) sum += x;
    int a = (sum + target) / 2;
    if (a < 0 || (sum + target) % 2 != 0) return 0;
    vector<vector<int>> dp(n + 1, vector<int>(a + 1));
    dp[0][0] = 1;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j <= a; j++)
        {
            dp[i][j] = j >= nums[i - 1] ? dp[i - 1][j] + dp[i - 1][j - nums[i - 1]] : dp[i - 1][j];
        }
    }
    return dp[n][a];
}

int lastStoneWeightII(vector<int>& stones) {
    int n = stones.size(), sum = 0;
    for (auto x : stones) sum += x;
    int aim = sum / 2;
    vector<vector<int>> dp(n + 1, vector<int>(aim + 1));
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j <= aim; j++)
        {
            dp[i][j] = dp[i - 1][j];
            if (j >= stones[i - 1]) dp[i][j] = max(dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]);
        }
    }
    return sum - 2 * dp[n][aim];
}

int main()
{
    vector<int> v{ 7,9,3,8,0,2,4,8,3,9 };
    findTargetSumWays(v, 0);
    lastStoneWeightII(v);

	return 0;
}